from django.db.models import Q
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU, SPU, GoodsCategory
from meiduo_admin.serializer.skus import SKUImageSerializer, SKUSimpleSerializer, SKUSerializer, CategorySerializer


class SKUImageViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = SKUImage.objects.all()
    lookup_value_regex = '\d+'

    serializer_class = SKUImageSerializer


class SKUSimpleView(ListAPIView):
    permission_class = [IsAdminUser]
    queryset = SKU.objects.all()
    serializer_class = SKUSimpleSerializer

    pagination_class = None


class SKUViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    lookup_value_regex = '\d+'

    def get_queryset(self):
        keyword = self.request.query_params.get("keyword")
        if keyword:
            queryset = SKU.objects.filter(Q(name__contains=keyword) | Q(caption__contains=keyword))
        else:
            queryset = SKU.objects.all()
        return queryset

    serializer_class = SKUSerializer


class CategoryView(ListAPIView):
    permission_classes = [IsAdminUser]
    queryset = GoodsCategory.objects.filter(id__gte=115)
    # def get_queryset(self):
    #     queryset=[]
    #     categories=GoodsCategory.objects.all()
    #     for category in categories:
    #         if category.subs.count ==0:
    #             queryset.append(category)
    serializer_class = CategorySerializer
    pagination_class = None